/**
 * Writed by yura and mak
 */

package wz.legend;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.apache.xerces.parsers.DOMParser;
import org.apache.commons.io.IOUtils;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * 
 * @author yura
 * 
 */
public class HttpContext {
    private static final String ENCODING = "utf-8";

    private HttpRequest request;
    private HttpResponse response;
    private DOMParser parser;

    public HttpContext(HttpRequest request, HttpResponse response) {
        this.request = request;
        this.response = response;
    }

    public Document getResponseDocument() throws IllegalStateException,
            SAXException, IOException {
        if (parser == null) {
            if (response.getEntity().getContentType().getValue()
                    .contains("xml")) {
                parser = new org.apache.xerces.parsers.DOMParser();
                parser
                        .parse(new InputSource(response.getEntity()
                                .getContent()));
            } else {
                String content = IOUtils.toString(response.getEntity()
                        .getContent(), "windows-1251");
                parser = new org.cyberneko.html.parsers.DOMParser();
                parser.parse(new InputSource(new ByteArrayInputStream(content
                        .getBytes("windows-1251"))));
            }
        }
        return parser.getDocument();
    }

    public HttpRequest getRequest() {
        return request;
    }

    public void setRequest(HttpRequest request) {
        this.request = request;
    }

    public HttpResponse getResponse() {
        return response;
    }

    public void setResponse(HttpResponse response) {
        this.response = response;
    }

}
